package com.iwuke.dance.gadget_view;

import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import com.iwuke.dance.wallet.e_coin.StickyHeaderDecoration;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author: 魏从响
 * @date: 2025/10/8
 */
public class StickyHeaderTouchListener implements RecyclerView.OnItemTouchListener {
    private GestureDetector mGestureDetector;
    private final RecyclerView recyclerView;
    private final StickyHeaderDecoration decoration;

    public StickyHeaderTouchListener(Context context, RecyclerView recyclerView,
                                     StickyHeaderDecoration decoration,int height) {
        this.recyclerView = recyclerView;
        this.decoration = decoration;

        mGestureDetector = new GestureDetector(context,
                new GestureDetector.SimpleOnGestureListener() {
                    @Override
                    public boolean onSingleTapUp(MotionEvent e) {
                        // 获取当前粘性头部视图
                        View headerView = decoration.getCurrentStickyView();
                        if (headerView != null) {
                            // 转换点击坐标到头部视图坐标系
                            int[] headerLocation = new int[2];
                            headerView.getLocationOnScreen(headerLocation);

                            float x = e.getRawX() - headerLocation[0];
                            float y = e.getRawY() - headerLocation[1] - height;

                            // 判断点击是否在头部视图范围内
                            if (x >= 0 && x < headerView.getWidth() &&
                                    y >= 0 && y < headerView.getHeight()) {
                                int position = decoration.getCurrentStickyPosition();
                                if (position != RecyclerView.NO_POSITION) {
                                    decoration.listener.onHeaderClick(position);
                                    return true;
                                }
                            }
                        }
                        return false;
                    }
                });
    }

    @Override
    public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
        return mGestureDetector.onTouchEvent(e);
    }

    @Override
    public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {}

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {}
}

